package com.bootmybatisdemo.demo.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class JwtUtils {

    private static Logger logger = LoggerFactory.getLogger(JwtUtils.class);

    //加密密钥，请勿泄漏
    private final static String salt = "JKKLJOoadsafa";

    //超时时间 单位秒
    public final static Long timeOut = 30 * 24 * 60 * 60L;

    /**
     * 生成jwt token
     * @param userId 用户id
     * @param subject 主体
     * @param map 数据
     * @return
     */
    public static String createJwt(Long userId, String subject, Map<String, Object> map) {
        long nowTime = System.currentTimeMillis();
        long expireTime = nowTime + timeOut * 1000;
        //创建jwt builder
        JwtBuilder jwtBuilder = Jwts.builder();
        //根据map设置claims
        jwtBuilder.setClaims(map);
        jwtBuilder.setId(String.valueOf(userId));
        jwtBuilder.setSubject(subject);
        jwtBuilder.setIssuedAt(new Date()); //设置当前时间
        jwtBuilder.signWith(SignatureAlgorithm.HS256, salt); //设置加密方式
        jwtBuilder.setExpiration(new Date(expireTime));//设置过期时间
        //创建token
        String token = jwtBuilder.compact();
        return token;
    }

    /**
     * 解析jwt 返回null则解析失败
     * @param token
     * @return
     */
    public static Claims parseJwt(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser().setSigningKey(salt).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            logger.error("解析token失败", e);
        }
        return claims;
    }

    /**
     * 根据token获取userId
     * @return
     */
    public static Integer parseUserId() {
        String jwtToken = RequestUtils.loginToken();
        if(jwtToken != null && !"".equals(jwtToken)){
            Claims claims = JwtUtils.parseJwt(jwtToken);
            String id = claims.getId();
            if(StringUtils.isNotEmpty(id)){
                return Integer.valueOf(id);
            }
        }
        return null;
    }




}
